package top.snoweagle.simple.console.security.auth;


import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.time.DateFormatUtils;
import top.snoweagle.simple.console.common.domain.http.RestResponse;
import top.snoweagle.simple.console.common.domain.http.UserSession;
import top.snoweagle.simple.console.common.domain.system.Permission;
import top.snoweagle.simple.console.common.domain.system.User;
import top.snoweagle.simple.console.common.enums.ResponseStatus;
import top.snoweagle.simple.console.common.enums.SessionInfo;
import top.snoweagle.simple.console.security.exception.AuthenticateException;
import top.snoweagle.simple.console.security.model.AuthorizationInfo;
import top.snoweagle.simple.console.service.system.PermissionService;
import top.snoweagle.simple.console.service.system.UserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 认证、授权
 */
@Component
public class RestfulAuthorizingProxy implements AuthorizingProxy {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private UserService userSerivce;
    @Autowired
    private TokenManager tokenManager;

    @Override
    public UserSession doGetAuthentication(String userName, String password) throws AuthenticateException{
        User user = userSerivce.queryUserByUserNameAndPasswd(userName, password);
        logger.info("登陆认证：用户：{}",userName,password);
        if (user != null) {
            logger.info("登陆认证成功！user：{}",user);
            return tokenManager.newUserSession(user.getUserId(),user.getFullName());
        } else {
            throw new AuthenticateException("用户名或密码错误");
        }
    }

    @Override
    public AuthorizationInfo doGetAuthorization(Long userId) {
        AuthorizationInfo info = new AuthorizationInfo();
        List<Permission> permissions =  permissionService.queryPermissionsByUserId(userId);

        List<String> ps = new ArrayList<>();
        for (Permission permission : permissions) {
            if (StringUtils.isNotBlank(permission.getPermission())) {
                ps.add(permission.getPermission());
            }
        }
        info.setPermissions(ps);
        info.setAccessMenus(permissionService.findUserMenuTree(userId));
        return info;
    }
    public RestResponse getIndexInfo(UserSession userSession, AuthorizationInfo authInfo) {
        RestResponse resp = new RestResponse();
        resp.setUserSession(userSession);
        resp.setStatus(ResponseStatus.SUCCESS.getCode());
        Map<String,Object> data =new HashMap<>();
        data.put(SessionInfo.AUTHINFO.getCode(), authInfo);
        data.put(SessionInfo.LOGIN_DATE.getCode(), DateFormatUtils.format(new Date(), "yyyyMMdd HH:mm:ss"));
        data.put("menus", JSON.toJSONString(authInfo.getAccessMenus()));
        resp.setData(data);
        resp.setMessage("成功");
        return resp;
    }
}
